package changechecker;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Random;

public class UrlChecker extends Thread { //my pride and joy, the URLchecker, this was the full application before I made the GUI
    //added by netbeans, don't know what it does.
    org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(changechecker.ChangeCheckerApp.class).getContext().getResourceMap(UrlChecker.class);
    String url; //string is made.
    ArrayList<String> sourceArray = new ArrayList<String>(); //new arraylist is created.
    Random randomgenerator = new Random(); //a randomgeneration is created
    String newSource; //a string with the new source is made
    int randomnum; //an int
    String[] urlList; //an array for the urls
    ChangeCheckerView parent; //we'll need the parent (changecheckerview), loaded with THIS in the app.
    public UrlChecker(String[] urlList, ChangeCheckerView parent) {
        try{
        this.parent = parent;
        
        this.urlList = urlList;
        randomnum = randomgenerator.nextInt(urlList.length); //a random number is chosen.
        url=urlList[randomnum]; //an url is picked
        for (String singleUrl : urlList){ //all sources of all urls are saved (because proxies usually have slightly different html one won't do)
            sourceArray.add(urlreader(singleUrl));
        }
        newSource  = urlreader(url);
        } catch (java.lang.NullPointerException ex){ //show an error when it fails.
                        this.parent.error("Could not connect to " + url + ", Check if it's correct and you have an internet connection");
        }
    }
    
    public void run() {
            try { //when running
            while (sourceArray.contains(newSource) && !newSource.equals("fail")) { //as long as there are no changes
                randomnum = randomgenerator.nextInt(urlList.length); //grab the source of a random url.
                newSource = urlreader(urlList[randomnum]);          //
            try {
                Thread.sleep(20000 / urlList.length); //and sleep for 20 seconds devided by the amount of URLS
            } catch (InterruptedException ex) {
                //do nothing
            }
        }
            if (newSource.equals("fail")){ //if an url fails to load, give an error.
                parent.error("Could not connect to " + urlList[randomnum] + ", Check if it's correct and you have an internet connection");
                return;
            } else {
            parent.siteUpdated();
            }
            } catch (java.lang.NullPointerException ex){ //and if we get an exception, error.
                        parent.error("Could not connect to " + urlList[randomnum] + ", Check if it's correct and you have an internet connection");
                        return;
            }
    }
    
    


    private String urlreader(String url) {
        try {
        String site = ""; //new string
        URL website = new URL(url); //URL is created with the placed url
        BufferedReader in = new BufferedReader( //a connection to the site is opened
                new InputStreamReader(
                website.openStream()));

        String inputLine;

        while ((inputLine = in.readLine()) != null) { //load all lines.
            site = site + inputLine;
        }
        in.close(); //close the connection
        return site; //and return it.
        } catch(IOException ex){ //and with problems, error...
            parent.error("Could not connect to " + url + ", Check if it's correct and you have an internet connection");
            return "fail";
            
        } catch (java.lang.NullPointerException ex){
            parent.error("Could not connect to " + url + ", Check if it's correct and you have an internet connection");
            return "fail";
        }
    }

    private String getHeader(String site) { //old version, kept for if needed, only checks last modified instead of the whole source. Does NOT work when using proxies
        try {


            URL url = new URL(site);
            URLConnection conn = url.openConnection();
            return conn.getHeaderField("Last-Modified");


        } catch (IOException ex) {
                    parent.error("Could not connect to " + url + ", Check if it's correct and you have an internet connection");
            return "fail";
        }

        



    }
    
    public void finished(){ //when finish, end the whole thing
        return;
    }
}